package mylab.io.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import mylab.base.foundation.lang.Callback;
import mylab.io.base.model.Msg;
import mylab.io.base.property.DasProperties;
import mylab.io.core.codec.Codec;
import mylab.io.core.context.CoreContext;
import mylab.io.core.util.NettyUtil;

/**
 * 自实现接入服务模板类
 * <>
 * server模式：一般只有2个 EventLoopGroup， 即2个独立的Reactor线程池
 * masterGroup：处理 NIO Accept 事件
 * childGroup： 处理 I/O 相关的读写操作
 * </>
 */
public abstract class AbstractServerDas<P extends DasProperties, M extends Msg, C extends Codec<P, M, F>, F>
        extends AbstractDas<P, M, C, F> {

    protected EventLoopGroup masterGroup, childGroup;

    protected ServerBootstrap bootstrap;

    public AbstractServerDas(CoreContext<P, M> context, C codec) {
        super(context, codec);
    }

    @Override
    protected void stopFunc(Callback<Void> callback) {
        try {
            NettyUtil.closeChannel(channel);
        } catch (Exception e) {
            e.printStackTrace(System.out);
        } finally {
            if (masterGroup != null) {
                masterGroup.shutdownGracefully();
            }
            if (childGroup != null) {
                childGroup.shutdownGracefully();
            }
            channel = null;
        }

        Callback.dealOnSuccess(callback);
    }
}
